"""
Phase 4: Regime Choice — Do Demographics Predict Exchange Rate Regimes?
=======================================================================
1. Ordered logit (sequential) for regime_3cat (1=peg, 2=intermediate, 3=float)
2. Binary logit: is_peg vs is_float (drop intermediate)
3. PanelGLS: regime transitions (regime_change as DV)
4. Z×KAOPEN interactions on regime choice
Hypothesis: aging → pegs (higher ERS, more rigid regimes)
"""

import pandas as pd
import numpy as np
from pathlib import Path
import sys
import warnings
warnings.filterwarnings('ignore')

PROJECT_DIR = Path(__file__).resolve().parent.parent
ROOT_DIR = PROJECT_DIR.parent
sys.path.insert(0, str(ROOT_DIR / "multilateral" / "src"))
from model import PanelGLS

DATA = PROJECT_DIR / "data" / "processed"
OUT_TABLES = PROJECT_DIR / "output" / "tables"
OUT_TABLES.mkdir(parents=True, exist_ok=True)

# OECD members (as of 2024, 38 countries)
OECD = {
    'AUS', 'AUT', 'BEL', 'CAN', 'CHL', 'COL', 'CRI', 'CZE', 'DNK', 'EST',
    'FIN', 'FRA', 'DEU', 'GRC', 'HUN', 'ISL', 'IRL', 'ISR', 'ITA', 'JPN',
    'KOR', 'LVA', 'LTU', 'LUX', 'MEX', 'NLD', 'NZL', 'NOR', 'POL', 'PRT',
    'SVK', 'SVN', 'ESP', 'SWE', 'CHE', 'TUR', 'GBR', 'USA',
}


def stars(p):
    if p < 0.01: return '***'
    if p < 0.05: return '**'
    if p < 0.1: return '*'
    return ''


def fmt(val, se, p):
    s = stars(p)
    return f"{val:.4f}{s}", f"({se:.4f})"


def run_panel_gls(df, y_var, x_vars, label):
    """Run PanelGLS and return results dict."""
    cols = [y_var] + x_vars + ['iso3', 'year']
    sub = df[cols].dropna()
    if len(sub) < 50:
        print(f"  {label}: insufficient obs ({len(sub)}), skipping")
        return None

    gls = PanelGLS()
    y = sub[y_var].values
    X = sub[x_vars].values
    try:
        gls.fit(y, X, sub['iso3'].values, sub['year'].values)
    except Exception as e:
        print(f"  {label}: GLS failed ({e}), skipping")
        return None

    result = {
        'model': label,
        'n_obs': gls.n_obs,
        'n_countries': gls.n_countries,
        'r_squared': gls.r_squared,
        'rho': gls.rho,
    }
    print(f"\n  {label} (N={gls.n_obs}, R²={gls.r_squared:.4f})")
    for i, name in enumerate(x_vars):
        sig = stars(gls.pvalues[i])
        print(f"    {name:30s} {gls.beta[i]:8.4f} ({gls.se[i]:.4f}) {sig}")
        result[f'{name}_coef'] = gls.beta[i]
        result[f'{name}_se'] = gls.se[i]
        result[f'{name}_p'] = gls.pvalues[i]

    return result


def run_logit(df, y_var, x_vars, label):
    """Pooled logit with Hessian SEs (manual implementation via BFGS)."""
    from scipy.optimize import minimize
    from scipy import stats as sp_stats

    cols = [y_var] + x_vars + ['iso3']
    sub = df[cols].dropna()
    if len(sub) < 50:
        print(f"  {label}: insufficient obs ({len(sub)}), skipping")
        return None

    y = sub[y_var].values.astype(float)
    X = np.column_stack([np.ones(len(sub)), sub[x_vars].values.astype(float)])
    n, k = X.shape

    # Check for sufficient variation
    if y.sum() < 5 or (1 - y).sum() < 5:
        print(f"  {label}: insufficient outcome variation (events={y.sum():.0f}), skipping")
        return None

    # Standardize X for numerical stability (except intercept)
    x_means = X[:, 1:].mean(axis=0)
    x_stds = X[:, 1:].std(axis=0)
    x_stds[x_stds == 0] = 1
    X_std = X.copy()
    X_std[:, 1:] = (X[:, 1:] - x_means) / x_stds

    def neg_log_likelihood(beta):
        z = X_std @ beta
        z = np.clip(z, -30, 30)
        p = 1 / (1 + np.exp(-z))
        p = np.clip(p, 1e-12, 1 - 1e-12)
        return -np.sum(y * np.log(p) + (1 - y) * np.log(1 - p))

    def gradient(beta):
        z = X_std @ beta
        z = np.clip(z, -30, 30)
        p = 1 / (1 + np.exp(-z))
        return -X_std.T @ (y - p)

    # Initial values
    beta0 = np.zeros(k)

    try:
        result = minimize(neg_log_likelihood, beta0, jac=gradient,
                         method='BFGS', options={'maxiter': 1000, 'gtol': 1e-6})
        if not result.success:
            print(f"  {label}: logit optimization did not converge, using result anyway")

        beta_std = result.x

        # Transform back to original scale
        beta = np.zeros(k)
        beta[1:] = beta_std[1:] / x_stds
        beta[0] = beta_std[0] - np.sum(beta_std[1:] * x_means / x_stds)

        # Hessian for standard errors
        z = X @ beta
        z = np.clip(z, -30, 30)
        p = 1 / (1 + np.exp(-z))
        W = p * (1 - p)
        H = X.T @ (X * W[:, None])

        try:
            V = np.linalg.inv(H)
            se = np.sqrt(np.diag(V))
        except np.linalg.LinAlgError:
            se = np.full(k, np.nan)

        t_stats = beta / se
        pvalues = 2 * (1 - sp_stats.norm.cdf(np.abs(t_stats)))

        # Pseudo-R² (McFadden)
        ll_model = -neg_log_likelihood(beta_std)
        p_bar = y.mean()
        ll_null = n * (p_bar * np.log(p_bar + 1e-12) + (1 - p_bar) * np.log(1 - p_bar + 1e-12))
        pseudo_r2 = 1 - ll_model / ll_null if ll_null != 0 else 0

        # Marginal effects at mean
        z_mean = X.mean(axis=0) @ beta
        p_mean = 1 / (1 + np.exp(-z_mean))
        mfx = beta[1:] * p_mean * (1 - p_mean)

    except Exception as e:
        print(f"  {label}: logit failed ({e}), skipping")
        return None

    res = {
        'model': label,
        'n_obs': n,
        'n_countries': sub['iso3'].nunique(),
        'r_squared': pseudo_r2,
        'rho': 0.0,
    }

    print(f"\n  {label} (N={n}, Pseudo-R²={pseudo_r2:.4f}) [Logit]")
    for i, name in enumerate(x_vars):
        sig = stars(pvalues[i + 1])
        print(f"    {name:30s} β={beta[i+1]:8.4f} (se={se[i+1]:.4f}) {sig}  "
              f"[MFX={mfx[i]:.5f}]")
        res[f'{name}_coef'] = mfx[i]  # Report marginal effects
        res[f'{name}_se'] = se[i + 1] * p_mean * (1 - p_mean)  # delta method approx
        res[f'{name}_p'] = pvalues[i + 1]

    return res


def write_table(results, filename, title):
    """Write regression results as markdown table."""
    if not results:
        return

    lines = [f"# {title}\n"]

    all_vars = []
    for r in results:
        for k in r:
            if k.endswith('_coef'):
                vname = k.replace('_coef', '')
                if vname not in all_vars:
                    all_vars.append(vname)

    model_labels = [r['model'] for r in results]
    header = "| Variable | " + " | ".join(model_labels) + " |"
    sep = "|:---|" + "|".join(["---:" for _ in results]) + "|"
    lines.append(header)
    lines.append(sep)

    for var in all_vars:
        coef_row = f"| {var} |"
        se_row = "| |"
        for r in results:
            if f'{var}_coef' in r:
                c, s = fmt(r[f'{var}_coef'], r[f'{var}_se'], r[f'{var}_p'])
                coef_row += f" {c} |"
                se_row += f" {s} |"
            else:
                coef_row += " |"
                se_row += " |"
        lines.append(coef_row)
        lines.append(se_row)

    lines.append("|:---|" + "|".join(["---:" for _ in results]) + "|")
    n_row = "| N |"
    r2_row = "| R² |"
    nc_row = "| Countries |"
    for r in results:
        n_row += f" {r['n_obs']} |"
        r2_row += f" {r['r_squared']:.4f} |"
        nc_row += f" {r['n_countries']} |"
    lines.append(n_row)
    lines.append(r2_row)
    lines.append(nc_row)

    lines.append("\n*Standard errors in parentheses. "
                 "Logit columns report marginal effects at means.*")
    lines.append("*\\*p<0.1, \\*\\*p<0.05, \\*\\*\\*p<0.01*")

    path = OUT_TABLES / filename
    path.write_text('\n'.join(lines))
    print(f"\n  Saved: {path}")


# ── 1. Ordered Logit (Sequential) ──────────────────────────────────────

def ordered_regime(df):
    """Sequential logit for regime_3cat: P(≥2) and P(≥3)."""
    print("\n" + "=" * 60)
    print("1. ORDERED REGIME CHOICE (SEQUENTIAL LOGIT)")
    print("=" * 60)

    controls = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth', 'kaopen']
    x_demo = ['Z_1', 'Z_2', 'Z_3']
    x_age = ['old_dep', 'youth_dep']

    results = []

    # --- Cutpoint 1: P(regime ≥ 2) i.e. intermediate or float vs peg ---
    df['regime_ge2'] = (df['regime_3cat'] >= 2).astype(float)
    # --- Cutpoint 2: P(regime ≥ 3) i.e. float vs peg/intermediate ---
    df['regime_ge3'] = (df['regime_3cat'] >= 3).astype(float)

    print(f"  regime_3cat distribution: {df['regime_3cat'].value_counts().sort_index().to_dict()}")
    print(f"  regime ≥ 2: {df['regime_ge2'].sum():.0f} / {df['regime_ge2'].notna().sum()}")
    print(f"  regime ≥ 3: {df['regime_ge3'].sum():.0f} / {df['regime_ge3'].notna().sum()}")

    # M1: Z → P(≥2) — move away from peg
    r = run_logit(df, 'regime_ge2', x_demo + controls, 'P(≥2): Z')
    if r: results.append(r)

    # M2: Z → P(≥3) — float vs rest
    r = run_logit(df, 'regime_ge3', x_demo + controls, 'P(≥3): Z')
    if r: results.append(r)

    # M3: Age composition → P(≥2)
    r = run_logit(df, 'regime_ge2', x_age + controls, 'P(≥2): Age')
    if r: results.append(r)

    # M4: Age composition → P(≥3)
    r = run_logit(df, 'regime_ge3', x_age + controls, 'P(≥3): Age')
    if r: results.append(r)

    write_table(results, "ordered_regime.md",
                "Ordered Regime Choice (Sequential Logit): Demographics → Regime")

    return results


# ── 2. Binary Logit: Peg vs Float ──────────────────────────────────────

def peg_vs_float(df):
    """Binary logit: is_peg vs is_float (drop intermediate)."""
    print("\n" + "=" * 60)
    print("2. BINARY LOGIT: PEG vs. FLOAT")
    print("=" * 60)

    # Filter to only peg and float observations
    binary_df = df[df['regime_3cat'].isin([1, 3])].copy()
    binary_df['is_peg_binary'] = (binary_df['regime_3cat'] == 1).astype(float)
    print(f"  Peg vs Float sample: {len(binary_df)} obs "
          f"(Peg={binary_df['is_peg_binary'].sum():.0f}, "
          f"Float={(1-binary_df['is_peg_binary']).sum():.0f})")

    controls = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth', 'kaopen']
    x_demo = ['Z_1', 'Z_2', 'Z_3']

    results = []

    # M1: Z → is_peg (baseline)
    r = run_logit(binary_df, 'is_peg_binary', x_demo + controls, 'Z baseline')
    if r: results.append(r)

    # M2: Age composition
    r = run_logit(binary_df, 'is_peg_binary',
                  ['old_dep', 'youth_dep'] + controls, 'Age')
    if r: results.append(r)

    # M3: Z + Z×KAOPEN interactions
    binary_df['Z_1_x_kaopen'] = binary_df['Z_1'] * binary_df['kaopen']
    binary_df['Z_2_x_kaopen'] = binary_df['Z_2'] * binary_df['kaopen']
    binary_df['Z_3_x_kaopen'] = binary_df['Z_3'] * binary_df['kaopen']
    interact_vars = x_demo + ['Z_1_x_kaopen', 'Z_2_x_kaopen', 'Z_3_x_kaopen'] + controls
    r = run_logit(binary_df, 'is_peg_binary', interact_vars, 'Z×KAOPEN')
    if r: results.append(r)

    # M4: OECD subsample
    oecd_df = binary_df[binary_df['iso3'].isin(OECD)].copy()
    print(f"  OECD peg/float sample: {len(oecd_df)} obs")
    r = run_logit(oecd_df, 'is_peg_binary', x_demo + controls, 'OECD only')
    if r: results.append(r)

    write_table(results, "peg_vs_float_logit.md",
                "Binary Logit: Peg vs. Float (Intermediate Dropped)")

    return results


# ── 3. Regime Transitions ──────────────────────────────────────────────

def regime_transitions(df):
    """PanelGLS with regime_change as DV."""
    print("\n" + "=" * 60)
    print("3. REGIME TRANSITIONS (PanelGLS)")
    print("=" * 60)

    controls = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth', 'kaopen']
    x_demo = ['Z_1', 'Z_2', 'Z_3']

    print(f"  regime_change events: {df['regime_change'].sum():.0f} / "
          f"{df['regime_change'].notna().sum()}")

    results = []

    # M1: Z → regime_change (full sample)
    r = run_panel_gls(df, 'regime_change', x_demo + controls, 'Full: Z')
    if r: results.append(r)

    # M2: Age → regime_change
    r = run_panel_gls(df, 'regime_change',
                      ['old_dep', 'youth_dep'] + controls, 'Full: Age')
    if r: results.append(r)

    # M3: Z + Z×KAOPEN → regime_change
    df['Z_1_x_kaopen'] = df['Z_1'] * df['kaopen']
    df['Z_2_x_kaopen'] = df['Z_2'] * df['kaopen']
    df['Z_3_x_kaopen'] = df['Z_3'] * df['kaopen']
    interact_vars = x_demo + ['Z_1_x_kaopen', 'Z_2_x_kaopen', 'Z_3_x_kaopen'] + controls
    r = run_panel_gls(df, 'regime_change', interact_vars, 'Z×KAOPEN')
    if r: results.append(r)

    # M4: OECD subsample
    oecd_df = df[df['iso3'].isin(OECD)].copy()
    r = run_panel_gls(oecd_df, 'regime_change', x_demo + controls, 'OECD')
    if r: results.append(r)

    write_table(results, "regime_transitions.md",
                "Regime Transitions: Demographics → Regime Change")

    return results


# ── Main ───────────────────────────────────────────────────────────────

def main():
    print("=" * 70)
    print("PHASE 4: REGIME CHOICE — DO DEMOGRAPHICS PREDICT EXCHANGE RATE REGIMES?")
    print("=" * 70)

    df = pd.read_csv(DATA / "trilemma_panel.csv")
    print(f"Panel: {len(df)} obs, {df['iso3'].nunique()} countries")
    print(f"Year range: {df['year'].min()}-{df['year'].max()}")

    # Ensure interaction terms exist
    if 'Z_1_x_kaopen' not in df.columns:
        df['Z_1_x_kaopen'] = df['Z_1'] * df['kaopen']
        df['Z_2_x_kaopen'] = df['Z_2'] * df['kaopen']
        df['Z_3_x_kaopen'] = df['Z_3'] * df['kaopen']

    # Summary of regime variables
    print(f"\nRegime 3-cat distribution:")
    if 'regime_3cat' in df.columns:
        print(df['regime_3cat'].value_counts().sort_index())
    print(f"\nis_peg: {df['is_peg'].sum():.0f}   is_float: {df['is_float'].sum():.0f}")
    print(f"regime_change events: {df['regime_change'].sum():.0f}")

    # 1. Ordered regime choice (sequential logit)
    ordered_regime(df)

    # 2. Binary logit: peg vs float
    peg_vs_float(df)

    # 3. Regime transitions
    regime_transitions(df)

    print("\n" + "=" * 70)
    print("PHASE 4 COMPLETE")
    print("=" * 70)


if __name__ == '__main__':
    main()
